package com.ruoyi.flowable.listener;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.flowable.domain.vo.FormDataVo;
import com.ruoyi.flowable.service.IFormDataService;
import com.ruoyi.system.service.ISysPostService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class FlowableGlobListener extends AbstractFlowableEngineEventListener {

    @Autowired
    private TaskService taskService;
    @Autowired
    private ISysPostService postService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IFormDataService formDataService;

    @Override
    public void taskCreated(FlowableEngineEntityEvent event) {
        Task task = (Task) event.getEntity();
        System.out.println();
        if ( null != task.getAssignee() && task.getAssignee().contains("STARTER_")){

            Long postId = Long.parseLong(task.getAssignee().substring(task.getAssignee().indexOf("__")+2));
            List<SysUser> sysUsers = new ArrayList<>();
            if (task.getAssignee().contains("STARTER_DEPT_POST__")) {
                Long starterDeptId = (Long) taskService.getVariable(task.getId(),"starterDeptId");
                //根据岗位id获取用户
                sysUsers = postService.selectUserNamesByPostIdAndDeptId(postId, starterDeptId);
            } else if (task.getAssignee().contains("STARTER_POST__")) {
                //根据岗位id获取用户
                sysUsers = postService.selectUserNamesByPostId(postId);
            }

            if (sysUsers.isEmpty()) {
                log.info("没有处理人");
                taskService.setAssignee(task.getId(), "test");
            } else if (sysUsers.size() == 1) {
                log.info("一个处理人");
                taskService.setAssignee(task.getId(), sysUsers.get(0).getUserName());
            } else {
                //多个人员时候处理
                log.info("多个处理人");
                taskService.setAssignee(task.getId(), null);
                sysUsers.forEach(user -> taskService.addCandidateUser(task.getId(), user.getUserName()));
            }
        }
    }

    @Override
    public void processCompleted(FlowableEngineEntityEvent event){
        ProcessInstance processInstance = (ProcessInstance) event.getEntity();
        try {
            FormDataVo formData = formDataService.selectFormDataByInstId(processInstance.getProcessInstanceId());
            if (formData == null){//发起直接结束formData是null
                runtimeService.updateBusinessStatus(processInstance.getProcessInstanceId(), "已完成");
                return;
            }
            String tableName = "form_" + formData.getFormId();
            Map<String, Object> map = new HashMap<>();
            map.put("data_id", formData.getDataId());
            Object stopType = runtimeService.getVariable(processInstance.getProcessInstanceId(),"stopType");
            String status = stopType == null ? "已完成" : stopType.toString();
            map.put("inst_status", status);

            runtimeService.updateBusinessStatus(processInstance.getProcessInstanceId(), status);

            formDataService.updateMapData(tableName, map);
        }catch (Exception e){
            log.error(e.getMessage());
        }

    }
}
